<script lang="ts">
    import { Checkbox } from "../Checkbox";
    import { useFormItemContext } from "../FormItem/FormItem.svelte";
    import { useClassList } from "../utils/useClassList";
    import type { CheckboxGroupProps } from "./CheckboxGroup";

    let { value = $bindable([]), ...props }: CheckboxGroupProps = $props();
    const ctx = useFormItemContext();

    const classList = $derived(
        useClassList(props, "cm-checkbox-group", {
            "cm-checkbox-group-stack": props.block,
            "cm-checkbox-group-card": props.type === "card",
            "cm-checkbox-group-pure-card": props.type === "pureCard",
        })
    );

    const _onChange = (checked: boolean, v: any) => {
        if (props.disabled) {
            return;
        }
        let val: any[] = value || [];
        if (checked) {
            if (!val.includes(v)) {
                val = val.concat(v);
            }
        } else {
            const index = val.indexOf(v);
            if (index > -1) {
                val.splice(index, 1);
            }
        }
        const newVal = JSON.parse(JSON.stringify(val));
        value = newVal;
        props.onchange?.(newVal);
        ctx?.onFieldChange?.();
    };

    const textField = props.textField || "label";
    const valueField = props.valueField || "value";
</script>

<div class={classList} style={props.style}>
    {#each props.data as item}
        {@const checked = value.includes(item[valueField])}
        <Checkbox disabled={props.disabled || item.disabled} value={item[valueField]} {checked} label={item[textField]} extra={item.extra} onchange={_onChange} />
    {/each}
</div>
